;; supercollider/server-boot.scm - (c) rohan drape, 2003-2005

;; The name of the SC3 server command, the path to search for UGen
;; plugins, and the path to search for SynthDef bytecode files.

(define-parameter server-command-name "scsynth")
(define-parameter server-plugin-path #f)
(define-parameter server-synthdef-path #f)

;; Server state.

(define (server-booted?)
  (server_-booted? (current-server)))

(define (set-server-booted?! value)
  (set-server_-booted?! (current-server) value))

;; Boot the server `server'.  It is an error if `server' is not local,
;; or is already booted.

(define (server-boot!)
  (if (server-plugin-path)
      (putenv "SC_PLUGIN_PATH" (server-plugin-path)))
  (if (server-synthdef-path)
      (putenv "SC_SYNTHDEF_PATH" (server-synthdef-path)))
  (if (not (server-local?))
      (error "server-boot: server not local" (server-host-name)))
  (if (server-booted?)
      (error "server-boot: server already booted" (server-host-name)))
  (system (format "~a ~a &"
		  (server-command-name) 
		  (server-options-string)))
  (thread-sleep! 1)
  (set-server-booted?! #t)
  (server-connect!)
  (-> "/g_new" 1 0 0))

;; Close an existing connection at `server' and send the '/quit'
;; command to the server.  It is an error if the server is not on the
;; local machine, is not booted, or is not connected,

(define (server-shutdown!)
  (if (not (server-local?))
      (error "server-shutdown: server not local" (server-host-name)))
  (if (not (server-booted?))
      (error "server-shutdown: server not booted" (server-host-name)))
  (if (not (server-connected?))
      (error "server-shutdown: server not connected" (server-host-name)))
  (-> "/quit")
  (server-disconnect!)
  (set-server-booted?! #f))
